﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using VirtualPress.Infrastructure.Entities.Entity;
using VirtualPress.Infrastructure.Entities;
using System.Linq.Expressions;
using VirtualPress.Infrastructure.Entities.Repository;
using VirtualPress.Infrastructure.Entities.Cache;
using VirtualPress.Tool.Framework;
using VirtualPress.Engine.ExServer.WorkPool;
using VirtualPress.Engine.ExServer.WorkPool.WorkHandle.Email;
using VirtualPress.Infrastructure.Entities.Enum;
using VirtualPress.Tool.Configration;
using System.Collections;
using System.Web;
using System.IO;
using VirtualPress.Infrastructure.Entities.JSONModel;
using VirtualPress.Portal.Biz.Content;

namespace VirtualPress.Portal.Biz
{
    public class JournalBiz
    {
        public static JournalType GetJournalType()
        {
            var username = HttpContext.Current.User.Identity.Name;
            var journalType = new Periodical().Find(c => c.Admin == username).Type;
            return (JournalType)journalType;
        }
        #region 期刊管理
        public static List<Periodical> GetNewJournalList(int pageSize, bool technicality)
        {
            using (Context ctx = new Context())
            {
                Expression<Func<T_Periodical, bool>> where = null;
                if (technicality)
                {
                    where = c => c.Type == (int)JournalType.technicality;
                }
                else
                {
                    where = c => true;
                }
                var data = ctx.Periodical.Where(where).OrderByDescending(c=>c.Id)
                           .Take(pageSize)
                           .Select(c=>new { c.Id, c.Name, c.Name_EN, c.Editor })
                           .ToList()
                           .Select(c => new Periodical()
                           {
                               Id = c.Id,
                               Name = c.Name,
                               Name_EN = c.Name_EN,
                               Editor = c.Editor
                           })
                           .ToList();
                return data;
            }
        }
        public static List<Periodical> GetAllJournal(Expression<Func<T_Periodical, bool>> where, int page, int pageSize)
        {
            using (Context ctx = new Context())
            { 
                var list = ctx.Periodical
                    .Where(where)
                    .OrderByDescending(c=>c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new Periodical().Set(c))
                    .ToList();
                return list;
            }
        }
        public static List<Periodical> GetAllJournal(int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.Periodical
                    .OrderByDescending(c => c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new Periodical().Set(c))
                    .ToList();
                return list;
            }
        }
        public static List<Periodical> GetJournalSnapshot(List<int> id)
        {
            List<Periodical> journals = new List<Periodical>();
            id.ForEach(c => {
                var item = new Periodical().Find(c.ToString());
                if (item != null)
                {
                    journals.Add(item);
                }
            });
            return journals;
        }
        public static List<Periodical> GetAllRelationJournal(Profession profession, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Periodical
                            where c.IsActive && c.IndType == (int)profession
                            orderby c.Id
                            select c)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new Periodical().Set(c))
                           .ToList();
                return data;

            }
        }
        public static int GetAllJournalForPage() 
        {
            using (Context ctx = new Context())
            {
                return ctx.Periodical.Count();
            }
        }
        public static int GetAllJournalForPage(Expression<Func<T_Periodical, bool>> where)
        {
            using (Context ctx = new Context())
            {
                return ctx.Periodical.Count(where);
            }
        }
        public static bool SaveNewJournal(Periodical journal)
        {
            if (new Periodical().Any(c => c.Name == journal.Name)) 
            {
                return false;
            }
            var user = new User().Find(journal.Admin);
            if (user != null)
            {
                return false;
            }
            
            var file = System.Web.HttpContext.Current.Request.Files["CoverImg"];
            if (file != null && file.ContentLength > 0)
            {
                string basedir = "/content/journal/" + journal.Name + "/coverimage/";
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }
                var fileinfo = new FileInfo(file.FileName);
                string filePath = basedir + journal.Name + "-converimage" + fileinfo.Extension;
                file.SaveAs(HttpContext.Current.Server.MapPath(filePath));
                journal.CoverImg = filePath;
            } 
            UserBiz.Register(
                 new User()
                 {
                     Area = 0,
                     Birthday = DateTime.Parse("1980-01-01"),
                     Email = journal.Admin,
                     Gender = Gender.Male,
                     IsActivate = true,
                     IsRefuse = false,
                     Location = 0,
                     NickName = journal.Name + "管理员",
                     Password = "123456",
                     Photo = journal.CoverImg,
                     Profession = 0,
                     RcdDate = DateTime.Now,
                     SystemRole = journal.Type == JournalType.technicality ? UserRole.JounalsAdmin : UserRole.MagazineAdmin,
                     UserName = journal.Admin
                 }, true);

            journal.DefaultExamineDay = 30;//默认审回时间为30天
            journal.ManuscriptTemplete = SiteResource.DefaultManuscritpsTemplete;
            journal.ManuscriptPageSize = SiteResource.DefaultPageSize;
            journal.PagePrice = SiteResource.DefaultPagePrice;
            journal.PricePerPrice = SiteResource.DefaultPricePerPage;
            journal.ExamineSheet = SiteResource.DefaultExamineSheet;
            journal.PublicationPrice = SiteResource.DefaultPublicationPrice;
            journal = journal.PostAdd();

            string toAdmin = EmailBuilder.BuildNewOrgIsCreateEmail(journal.Name, OrganizationType.Journal, journal.Admin);
            if (!String.IsNullOrEmpty(toAdmin))
            {
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify, new NormalNotifyEmail()
                {
                    Message = toAdmin,
                    Recipient = journal.Email,
                    Title = "期刊 \"" + journal.Name + "\" 已经创建"
                });
            }
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="choose">1:启用期刊 0:停用期刊</param>
        /// <returns></returns>
        public static bool Enable(int id, int choose)
        {
            var journal = new Periodical().Find(id.ToString());
            if (journal != null)
            {
                journal.IsActive = choose == 1;
                if (journal.PostModify() != null)
                {
                    return true;
                }
            }
            return false;
        }
        public static bool Delete(int id)
        {
            var journal = new Periodical().Find(id.ToString());
            if (journal != null)
            {
                return journal.PostDelete() != null;
            }
            return false;
        }
        public static List<Favour> GetFavour(string userName, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                List<Favour> data = new List<Favour>();

                data = (from c in ctx.Article
                        join j in ctx.Periodical
                        on c.Peri_Id equals j.Id
                        where c.UserName == userName
                        select new { j.Name, j.IndType, j.Id, c.CreateTime, c.Peri_Id, MansId = c.Id })
                            .GroupBy(c => c.Peri_Id)
                            .OrderByDescending(c => c.Key)
                            .Skip(page * pageSize)
                            .Take(pageSize)
                            .ToList()
                            .Select(c => new Favour()
                            {
                                JournalId = c.Key,
                                ArticleNum = c.Count(),
                                IndType = (Profession)c.FirstOrDefault().IndType,
                                JournalName = c.FirstOrDefault().Name,
                                LastRecord = c.OrderByDescending(o => o.Id).FirstOrDefault().CreateTime
                            })
                            .ToList();
                return data;
            }
        }
        public static int GetFavourForPage(string userName)
        {
            using (Context ctx = new Context())
            {
                 return (from c in ctx.Article
                            join j in ctx.Periodical
                            on c.Peri_Id equals j.Id
                            where c.UserName == userName
                            select new { j.Name, j.IndType, j.Id, c.CreateTime, c.Peri_Id })
                            .GroupBy(c => c.Peri_Id)
                            .Count();
            }
        }
        #endregion

        #region 稿件管理
        /// <summary>
        /// 稿件修订
        /// </summary>
        /// <param name="articleId"></param>
        public static void ArticleEdit(int articleId)
        {
            var article = new Article().Find(articleId.ToString());
            if (article == null || article.UserName != HttpContext.Current.User.Identity.Name ||
                !(article.Status == ArticleStatus.ZhuanShenXiuDing || article.Status == ArticleStatus.ZhongShenXiuDing))
            {
                return; 
            }
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            string basedir = "/content/journal/" + journal.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
            var file = HttpContext.Current.Request.Files["Appendix"];
            string appendixPath = string.Empty;
            string appendixName = string.Empty;
            string appendixCode = string.Empty;
            string format = string.Empty;
            string size = string.Empty;
            if (file != null && file.ContentLength > 0)
            {
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }
                appendixCode = new StreamFactory().BuildArticleAppendixCodeStreamNo(article.Code, AttachmentStatus.XiuDingGao, article.Id);

                var fileInfo = new FileInfo(file.FileName);
                size = Math.Round(
                    decimal.Parse(file.ContentLength.ToString()) / 1024,
                    2).ToString() + " KB";
                string extendName = fileInfo.Extension;
                format = extendName.Replace(".", "").ToUpper();
                appendixName = fileInfo.Name.Replace(extendName, "");

                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + extendName));
                appendixPath = basedir + appendixCode + extendName;
            }
            if (!String.IsNullOrEmpty(appendixPath))
            {
                //创建新附件
                var attachment = new Appendix()
                {
                    AttachmentType = AttachmentType.Manuscript,
                    AppendixCode = appendixCode,
                    CreateTime = DateTime.Now,
                    FileName = appendixName,
                    Path = appendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId = article.Id,
                    AttachmentStatus = AttachmentStatus.XiuDingGao,
                    Format=format,
                    Size=size
                };
                attachment.PostAdd();
            }
            if (article.Status == ArticleStatus.ZhuanShenXiuDing)
            {
                //创建历史记录
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhuanShenXiuDingWanCheng,
                    ManuscriptId = article.Id,
                    Message = "专审修订完成",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();
                article.Status = ArticleStatus.ZhuanShenXiuDingWanCheng;
                article.PostModify();
            }
            else if (article.Status == ArticleStatus.ZhongShenXiuDing)
            {
                //创建历史记录
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhongShenXiuDingWanCheng,
                    ManuscriptId = article.Id,
                    Message = "终审修订完成",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();
                article.Status = ArticleStatus.ZhongShenXiuDingWanCheng;
                article.PostModify();
            }
        }
        public static bool ArticleEdit(Article article, List<string> authorList)
        {
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            string basedir = "/content/journal/" + journal.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
            var file = HttpContext.Current.Request.Files["Appendix"];
            string appendixPath = string.Empty;
            string appendixCode = string.Empty;
            string appendixName = string.Empty;
            string format = string.Empty;
            string size = string.Empty;
            if (file != null && file.ContentLength > 0)
            {
                appendixCode = new StreamFactory().BuildArticleAppendixCodeStreamNo(article.Code, AttachmentStatus.ChuGao, article.Id);
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }

                var fileInfo = new FileInfo(file.FileName);
                size = Math.Round(
                    decimal.Parse(file.ContentLength.ToString()) / 1024,
                    2).ToString() + " KB";
                string extendName = fileInfo.Extension;
                format = extendName.Replace(".", "").ToUpper();
                appendixName = fileInfo.Name.Replace(extendName, "");
                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + extendName));
                appendixPath = basedir + appendixCode + extendName;
            }
            if (!String.IsNullOrEmpty(appendixPath))
            { 
                //删除原有附件
                var attachment = new Appendix().Find(c=>c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(attachment.Path)))
                {
                    try
                    {
                        System.IO.File.Delete(HttpContext.Current.Server.MapPath(attachment.Path));
                    }
                    catch(Exception e) 
                    {
                        LogHelper.Write(CommonLogger.Journal, LogLevel.Error, e);
                    }
                }
                //删除原附件
                attachment.PostDelete();
                //创建新附件
                attachment = new Appendix()
                {
                    AttachmentType = AttachmentType.Manuscript,
                    AppendixCode = appendixCode,
                    CreateTime = DateTime.Now,
                    FileName = appendixName,
                    Path = appendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId=article.Id,
                    AttachmentStatus = AttachmentStatus.ChuGao,
                    Format =format,
                    Size=size
                };
                attachment.PostAdd();
            }

            var recommendation = HttpContext.Current.Request.Files["Recommendation"];
            string recommendationAppendixPath = string.Empty;
            string recommendationAppendixName = string.Empty;
            if (recommendation != null && recommendation.ContentLength > 0)
            {
                var fileInfo = new FileInfo(recommendation.FileName);
                string extendName = fileInfo.Extension;
                recommendationAppendixName = fileInfo.Name.Replace(extendName, "");

                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + "-recommand" + extendName));
                recommendationAppendixPath = basedir + appendixCode + "-recommand" + extendName;
            }
            if (!String.IsNullOrEmpty(recommendationAppendixPath))
            {
                //删除原有推荐材料
                var attachment = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(attachment.Path)))
                {
                    try
                    {
                        System.IO.File.Delete(HttpContext.Current.Server.MapPath(attachment.Path));
                    }
                    catch (Exception e)
                    {
                        LogHelper.Write(CommonLogger.Journal, LogLevel.Error, e);
                    }
                }
                //删除原推荐材料
                attachment.PostDelete();
                //创建新推荐材料
                attachment = new Appendix()
                {
                    AttachmentType = AttachmentType.Recommendation,
                    AppendixCode = appendixCode + "-recommand",
                    CreateTime = DateTime.Now,
                    FileName = recommendationAppendixName,
                    Path = recommendationAppendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId = article.Id
                };
                attachment.PostAdd();
            }


            //创建稿件历史
            var history = new ArticleHistory()
            {
                ManuscriptId = article.Id,
                CreateTime = DateTime.Now,
                CurrentStatus = article.Status,
                Message = "修订稿件",
                Operator = HttpContext.Current.User.Identity.Name,
                PreStatus = article.Status
            };
            history.PostAdd();

            //删除员稿件作者成员记录
            var articleAuthor = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            if(authorList != null && authorList.Any())
            {
                articleAuthor.ForEach(c=>c.PostDelete());
            }
            //创建期刊作者
            foreach (var item in authorList)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    var writer = new Author().Find(item);
                    if (writer != null)
                    {
                        var author = new ArticleAuthor()
                        {
                            AuthorId = writer.Id,
                            AuthorName = writer.LastName + " " + writer.FirstName,
                            ManuscriptId = article.Id
                        }.PostAdd();
                        if (author == null)
                        {
                            LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件作者失败，请手工处理" + Environment.NewLine + author.ToJson());
                        }
                    }
                }
            }

            return article.PostModify()!= null;
        }
        public static bool Contribute(Article article, List<string> authorlist)
        {
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            article.Code = new StreamFactory().BuildArticleStreamNo(journal.ShortName, BuildStreamType.Manuscript, journal.Id);
            //创建稿件
            article.PostAdd();

            if (article == null)
            {
                LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件失败。" + Environment.NewLine + article.ToJson());
                return false;
            }
            var file = HttpContext.Current.Request.Files["Appendix"];
            Appendix attachment = null;
            string basedir = "/content/journal/" + journal.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
            string appendixPath = string.Empty;
            string appendixCode = string.Empty;
            string format = string.Empty;
            string size = string.Empty;
            if (file != null && file.ContentLength > 0)
            {
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }
                appendixCode = new StreamFactory().BuildArticleAppendixCodeStreamNo(article.Code, AttachmentStatus.ChuGao, article.Id);
                var fileInfo = new FileInfo(file.FileName);
                size = Math.Round(
                    decimal.Parse(file.ContentLength.ToString()) / 1024, 
                    2).ToString() + " KB";
                string extendName = fileInfo.Extension;
                format = extendName.Replace(".","").ToUpper();
                string fileName = fileInfo.Name.Replace(extendName, "");
                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + extendName));
                appendixPath = basedir + appendixCode + extendName;

                //创建附件
                attachment = new Appendix()
                {
                    AttachmentType = AttachmentType.Manuscript,
                    AppendixCode = appendixCode,
                    CreateTime = DateTime.Now,
                    FileName = fileName,
                    Path = appendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId = article.Id,
                    AttachmentStatus = AttachmentStatus.ChuGao,
                    Format=format,
                    Size=size
                };
                attachment.PostAdd();
                if (attachment == null)
                {
                    LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件附件失败，请手工处理" + Environment.NewLine + attachment.ToJson());
                }
            }

            var recommendation = HttpContext.Current.Request.Files["Recommendation"];
            string recommendationAppendixPath = string.Empty;

            if (attachment != null && recommendation != null && recommendation.ContentLength > 0)
            {
                var fileInfo = new FileInfo(recommendation.FileName);
                string extendName = fileInfo.Extension;
                string fileName = fileInfo.Name.Replace(extendName, "");
                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + attachment.AppendixCode + "-recommand" + extendName));
                recommendationAppendixPath = basedir + attachment.AppendixCode + "-recommand" + extendName;

                //创建附件
                var recommand = new Appendix()
                {
                    AttachmentType = AttachmentType.Recommendation,
                    AppendixCode = attachment.AppendixCode + "-recommand",
                    CreateTime = DateTime.Now,
                    FileName = fileName,
                    Path = recommendationAppendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId = article.Id
                };
                recommand.PostAdd();
                if (recommand == null)
                {
                    LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件推荐书失败，请手工处理" + Environment.NewLine + attachment.ToJson());
                }
            }

            //创建稿件历史
            new ArticleHistory()
            {
                CreateTime = DateTime.Now,
                CurrentStatus = ArticleStatus.Open,
                Message = "投稿成功",
                Operator = HttpContext.Current.User.Identity.Name,
                PreStatus = ArticleStatus.Open,
                ManuscriptId = article.Id
            }.PostAdd();


            new AuditingRecord()
            {
                CreateTime = DateTime.Now,
                Distributor = "system",
                ExamineStatus = ExamineStatus.DaiShenHe,
                JournalId = article.Peri_Id,
                LastRecord = DateTime.Now,
                ManuscriptId = article.Id,
                Step = ExamineStep.ChuShen,
                UserName = journal.Admin,
                SuggestStatus = 0
            }.PostAdd();
            
            //创建期刊作者
            foreach (var item in authorlist)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    var writer = new Author().Find(item);
                    if (writer != null)
                    {
                        var author = new ArticleAuthor()
                        {
                            AuthorId = writer.Id,
                            AuthorName = writer.LastName + writer.FirstName,
                            ManuscriptId = article.Id
                        }.PostAdd();
                        if (author == null)
                        {
                            LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件作者失败，请手工处理" + Environment.NewLine + author.ToJson());
                        }
                    }
                }
            }
            string toAuthor = EmailBuilder.BuildContributeEmail(article.Id);
            if (!String.IsNullOrEmpty(toAuthor))
            {
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                new NormalNotifyEmail()
                {
                    Message = toAuthor,
                    Title = String.Format("{0} 投稿成功", article.Title),
                    Recipient = article.UserName
                });
            }

            string toOrg = EmailBuilder.BuildNewArticleIncomeEmail(article.Id, OrganizationType.Journal, journal.Id);
            if (!String.IsNullOrEmpty(toOrg))
            {
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                    new NormalNotifyEmail()
                    {
                        //BackUrl = "/workspace/console/article?type=0",
                        Message = toOrg,
                        Title = "您的期刊收到一封新稿件",
                        Recipient = journal.Email
                    });
            }
            return true;
        }
        public static bool ManualArticle(Article article, List<string> authorlist)
        {
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            if(journal == null){
                return false;
            }
            //创建稿件
            article.PostAdd();
            if (article == null)
            {
                LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件失败。" + Environment.NewLine + article.ToJson());
                return false;
            }
            article.Code = new StreamFactory().BuildArticleStreamNo(journal.ShortName, BuildStreamType.Manuscript, journal.Id);
            article.PostModify();

            var file = HttpContext.Current.Request.Files["Appendix"];
            string appendixPath = string.Empty;
            string appendixCode = string.Empty;
            string appendixName = string.Empty;
            string format = string.Empty;
            string size = string.Empty;
            if (file != null && file.ContentLength > 0)
            {
                appendixCode = new StreamFactory().BuildArticleAppendixCodeStreamNo(
                    article.Code, AttachmentStatus.DingGao, article.Id);
                string basedir = "/content/journal/" + journal.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }
                size = Math.Round(
                     decimal.Parse(file.ContentLength.ToString()) / 1024,
                     2).ToString() + " KB";
                var fileInfo = new FileInfo(file.FileName);
                string extendName = fileInfo.Extension;
                format = extendName.Replace(".", "").ToUpper();
                appendixName = fileInfo.Name.Replace(extendName, "");

                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + extendName));
                appendixPath = basedir + appendixCode + extendName;

                //创建附件
                var attachment = new Appendix()
                {
                    AttachmentType = AttachmentType.Manuscript,
                    AppendixCode = appendixCode,
                    CreateTime = DateTime.Now,
                    FileName = appendixName,
                    Path = appendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId = article.Id,
                    AttachmentStatus = AttachmentStatus.DingGao,
                    Format=format,
                    Size=size
                };
                attachment.PostAdd();
                if (attachment == null)
                {
                    LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件附件失败，请手工处理" + Environment.NewLine + attachment.ToJson());
                }
            }
            //创建稿件历史
            var history = new ArticleHistory()
            {
                CreateTime = DateTime.Now,
                CurrentStatus = ArticleStatus.ChuBanYiJiaoFei,
                Message = "管理员手工维护",
                Operator = HttpContext.Current.User.Identity.Name,
                PreStatus = ArticleStatus.Open
            };
            history.ManuscriptId = article.Id;
            history.PostAdd();
            //创建期刊作者
            foreach (var item in authorlist)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    var writer = new Author().Find(item);
                    if (writer != null)
                    {
                        var author = new ArticleAuthor()
                        {
                            AuthorId = writer.Id,
                            AuthorName = writer.LastName + writer.FirstName,
                            ManuscriptId = article.Id
                        }.PostAdd();
                        if (author == null)
                        {
                            LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件作者失败，请手工处理" + Environment.NewLine + author.ToJson());
                        }
                    }
                }
            }
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="where"></param>
        /// <param name="loadexaminedetail"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<Article> GetAllArticle(Expression<Func<T_Article, bool>> where,bool loadexaminedetail, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.Article
                    .Where(where)
                    .Join(
                        ctx.Periodical,
                        m => m.Peri_Id,
                        p => p.Id,
                        (m, p) => new { m, p })
                    .Join(
                        ctx.ArticleAuthor,
                        c => c.m.Id,
                        a => a.ManuscriptId,
                        (c, a) => new { c, a })
                    .GroupJoin(
                        ctx.PeriodicalItem.DefaultIfEmpty(),
                        c => c.c.m.PeriItem_Id,
                        i => i.Id,
                        (c, i) => new { c, i })
                    .GroupBy(c => c.c.c.m.Id)
                    .OrderByDescending(c => c.Key)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new Article().Set(c.FirstOrDefault().c.c.m)
                    .SetJournalItemCode(c.FirstOrDefault().i.Any() ? c.FirstOrDefault().i.FirstOrDefault().Manuscriptcode : String.Empty)
                    .LoadJournal(new Periodical().Set(c.FirstOrDefault().c.c.p))
                    .LoadArticleAuthor(c.Select(o => new ArticleAuthor().Set(o.c.a)).ToList()))
                    .ToList();
                if (loadexaminedetail)
                {
                    var keys =list.Select(m => m.Id).ToList();
                    var records = ctx.AuditingRecord.Where(c =>
                        keys.Contains(c.ManuscriptId) && c.Step == (int)ExamineStep.ZhuanShen)
                        .GroupBy(c=>c.ManuscriptId)
                        .ToList();
                    foreach (var article in list) 
                    {
                        var item = records.FirstOrDefault(c => c.Key == article.Id);
                        article.ExamineTotle = item.Count(c => c.ExamineStatus == (int)ExamineStatus.DaiShenHe || c.ExamineStatus == (int)ExamineStatus.WanCheng);
                        article.ExamineComplete = item.Count(c => c.ExamineStatus == (int)ExamineStatus.WanCheng);
                    }
                }

                return list;
            }
        }
        public static List<Article> GetAllArticle(Expression<Func<T_Article, bool>> where, int page, int pageSize)
        {
            return GetAllArticle(where, false, page, pageSize);
        }
        
        /// <summary>
        /// 获取已经出版的稿件快照信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<Article> GetAllArticleSnapshot(int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Article
                            join a in ctx.ArticleAuthor
                             on c.Id equals a.ManuscriptId
                            join f in ctx.Appendix
                             on c.Id equals f.RaletionId
                            join j in ctx.Periodical
                             on c.Peri_Id equals j.Id
                            join ji in ctx.PeriodicalItem
                             on c.PeriItem_Id equals ji.Id into journalItem
                            from ji in journalItem.DefaultIfEmpty()
                            where f.Type == (int)AttachmentType.Manuscript && f.Status == 9 && c.Status == (int)ArticleStatus.YiChuBan
                            group new { c, a, f,j.Name, ji } by c.Id into g
                            orderby g.Key descending
                            select g)
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList();
                var result = data
                           .Select(c => new Article().Set(c.FirstOrDefault().c)
                               .LoadJournalItem(c.FirstOrDefault().ji == null?null:new PeriodicalItem().Set(c.FirstOrDefault().ji))
                               .LoadJournal(new Periodical(){Name = c.FirstOrDefault().Name})
                               .LoadArticleAuthor(c.Select(i => new ArticleAuthor().Set(i.a)).ToList())
                               .LoadAttachment(c.Select(i => new Appendix().Set(i.f)).ToList()))
                           .ToList();
                return result;
            }
        }
        /// <summary>
        /// 获取期刊已经出版的稿件快照信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<Article> GetAllArticleSnapshot(int journalId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Article
                            join a in ctx.ArticleAuthor
                             on c.Id equals a.ManuscriptId
                            join f in ctx.Appendix
                             on c.Id equals f.RaletionId
                            where c.Peri_Id == journalId && f.Type == (int)AttachmentType.Manuscript && c.Status == (int)ArticleStatus.YiChuBan
                            group new { c, a, f } by c.Id into g
                            orderby g.Key descending
                            select g)
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new Article().Set(c.FirstOrDefault().c)
                               .LoadArticleAuthor(c.Select(i => new ArticleAuthor().Set(i.a)).ToList())
                               .LoadAttachment(c.Select(i => new Appendix().Set(i.f)).ToList()))
                           .ToList();
                return data;
            }
        }
        public static int GetAllArticleForPage(Expression<Func<T_Article, bool>> where)
        {
             using (Context ctx = new Context())
            {
                return ctx.Article.Count(where);
             }
        }
        public static void CancelArticle(int id)
        {
            var article = new Article().Find(c => c.Id == id && c.UserName == System.Web.HttpContext.Current.User.Identity.Name && c.ArticleType == (int)ArticleType.Journal && !c.IsDelete && (c.Status == 0 || c.Status == 99));
            if (article != null)
            {
                article.IsDelete = true;
                article.PostModify();
                //创建稿件历史
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = article.Status,
                    ManuscriptId = article.Id,
                    Message = "删除稿件",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();
            }
        }
        public static void CancelArticleForJournal(int id)
        {
            string userName = HttpContext.Current.User.Identity.Name;
            var user = new User().Find(userName);
            if (String.IsNullOrEmpty(userName) || user == null)
            {
                return;
            }

            var article = new Article().Find(c => c.Id == id && !c.IsDelete);
            if (article == null)
            {
                return;
            }

            var journal = new Periodical().Find(c => c.Id == article.Peri_Id);
            if (journal == null || !(journal.Admin.ToLower() == userName.ToLower() || user.SystemRole == UserRole.Admin))
            {
                return;
            }
            article.IsDelete = true;
            article.PostModify();

            //创建稿件历史
            new ArticleHistory()
            {
                CreateTime = DateTime.Now,
                CurrentStatus = article.Status,
                ManuscriptId = article.Id,
                Message = "期刊管理员删除稿件",
                Operator = HttpContext.Current.User.Identity.Name,
                PreStatus = article.Status
            }.PostAdd();
        }
        public static List<ArticleHistory> GetAllArticleHistory(int articleId)
        {
            using (Context ctx = new Context())
            {
                return ctx.ArticleHistory
                    .Where(c => c.ManuscriptId == articleId)
                    .ToList()
                    .Select(c => new ArticleHistory().Set(c))
                    .ToList();
            }
        }
        public static bool DoManuscriptCheck(Article article, int Page, bool optionsRadios, string RefuseMessage)
        {
            Periodical journal = new Periodical().Find(article.Peri_Id.ToString());
            if (article != null && journal != null)
            {
                if (optionsRadios)
                {
                    var record = new AuditingRecord().Find(
                        c => c.Step == 1 && c.ExamineStatus == 1 && c.ManuscriptId == article.Id);
                    if (record != null)
                    {
                        record.ExamineStatus = ExamineStatus.WanCheng;
                        record.Message = "初审通过";
                        record.PostModify();
                    }

                    var recommendation = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
                    if (recommendation != null)
                    {
                        new ArticleHistory()
                        {
                            CreateTime = DateTime.Now,
                            CurrentStatus = ArticleStatus.ZhongShen,
                            ManuscriptId = article.Id,
                            Message = "专家推荐 - 进入终审",
                            Operator = HttpContext.Current.User.Identity.Name,
                            PreStatus = article.Status
                        }.PostAdd();
                        article.PageSize = Page;
                        article.Status = ArticleStatus.ZhongShen;
                        article.PostModify();
                        string toAuthor = EmailBuilder.BuildAcceptArticleWithCommandSheetEmail(article.Title, article.UserName);
                        if (!String.IsNullOrEmpty(toAuthor)) {
                            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                            new NormalNotifyEmail()
                            {
                                //BackUrl = "/workspace/console/article?type=0",
                                Message = toAuthor,
                                Title = "稿件《" + article.Title + "》初审完成",
                                Recipient = journal.Email
                            });
                        }
                        //WorkPool.Append<ManuscriptCheckEmail>(WorkType.email_for_manuscriptcheck,
                        //   new ManuscriptCheckEmail()
                        //   {
                        //       ArticleName = article.Title,
                        //       Recipient = article.UserName,
                        //       Message = String.Format("",
                        //       article.Title),
                        //       BackUrl = string.Empty
                        //   });
                    }
                    else
                    {
                        new ArticleHistory()
                        {
                            CreateTime = DateTime.Now,
                            CurrentStatus = ArticleStatus.ZhuanShenDaiJiaoFei,
                            ManuscriptId = article.Id,
                            Message = "初审通过",
                            Operator = HttpContext.Current.User.Identity.Name,
                            PreStatus = article.Status
                        }.PostAdd();
                        if (journal.IsFeeForExpertExmaine)
                        {
                            article.Status = ArticleStatus.ZhuanShenDaiJiaoFei;
                        }
                        else
                        {
                            new ArticleHistory()
                            {
                                CreateTime = DateTime.Now,
                                CurrentStatus = ArticleStatus.ZhuanShenDaiFenPei,
                                ManuscriptId = article.Id,
                                Message = "免专审费",
                                Operator = HttpContext.Current.User.Identity.Name,
                                PreStatus = ArticleStatus.ZhuanShenDaiJiaoFei
                            }.PostAdd();
                            article.Status = ArticleStatus.ZhuanShenDaiFenPei;
                        }
                        article.PageSize = Page;
                        article.PostModify();

                        if (journal.IsFeeForExpertExmaine)
                        {
                            int totalPay = journal.ManuscriptPageSize >= Page ? journal.PagePrice : (Page - journal.ManuscriptPageSize) * journal.PricePerPrice + journal.PagePrice;

                            var bill = new Reckoning()
                            {
                                CreateTime = DateTime.Now,
                                Message = String.Format("期刊《{0}》专审费用", article.Title),
                                Own = article.UserName,
                                PayFor = 0,
                                RaletionId = article.Id,
                                Status = 0,
                                TotalPay = totalPay
                            }.PostAdd();
                            if (bill == null)
                            {
                                LogHelper.Write(CommonLogger.Journal, LogLevel.Error,
                                    "稿件" + article.Id + "记录代缴费记录失败，请人工处理");
                            }
                        }
                        string toAuthor = EmailBuilder.BuildFirstExaminationEmail(article.Title, article.UserName,journal.IsFeeForExpertExmaine);
                        if (!String.IsNullOrEmpty(toAuthor))
                        {
                            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                            new NormalNotifyEmail()
                            {
                                //BackUrl = "/workspace/console/article?type=0",
                                Message = toAuthor,
                                Title = "稿件《" + article.Title + "》初审完成",
                                Recipient = journal.Email
                            });
                        }
                        //WorkPool.Append<ManuscriptCheckEmail>(WorkType.email_for_manuscriptcheck,
                        //   new ManuscriptCheckEmail()
                        //   {
                        //       ArticleName = article.Title,
                        //       Recipient = article.UserName,
                        //       Message = String.Format("您的稿件《{0}》初审通过，请尽快缴费以进行专审。：<br/>您的稿件一共{1}页，共需缴费：人民币 {2}元，如有疑问请与期刊方联系。",
                        //       article.Title, Page, totalPay),
                        //       BackUrl = "/workspace/member/bill"
                        //   });
                    }
                }
                else
                {
                    new ArticleHistory()
                    {
                        CreateTime = DateTime.Now,
                        CurrentStatus = ArticleStatus.Close,
                        ManuscriptId = article.Id,
                        Message = "初审不通过",
                        Operator = HttpContext.Current.User.Identity.Name,
                        PreStatus = article.Status
                    }.PostAdd();
                    article.Status = ArticleStatus.Close;
                    article.PostModify();

                    new AuditingRecord()
                    {
                        CreateTime = DateTime.Now,
                        Distributor = HttpContext.Current.User.Identity.Name,
                        ExamineStatus = ExamineStatus.QuXiao,
                        JournalId = journal.Id,
                        ManuscriptId = article.Id,
                        Message = "初审不通过",
                        Step = ExamineStep.ChuShen,
                        UserName = HttpContext.Current.User.Identity.Name
                    }.PostAdd();

                    var attachment = new Appendix().Find(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
                    if (attachment != null)
                    {
                        attachment.Suggestion = RefuseMessage;
                        attachment.PostModify();
                    }

                    string toAuthor = EmailBuilder.BuildFirstExaminationNotPassEmail(article.Title,
                        article.UserName, RefuseMessage);
                    if (!String.IsNullOrEmpty(toAuthor))
                    {
                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Message = toAuthor,
                            Title = "您的稿件《" + article.Title + "》初审未通过",
                            Recipient = journal.Email
                        });
                    }
                    //WorkPool.Append<ManuscriptCheckEmail>(WorkType.email_for_manuscriptcheck,
                    //    new ManuscriptCheckEmail()
                    //    {
                    //        ArticleName = article.Title,
                    //        Recipient = article.UserName,
                    //        Message = String.Format("您的稿件《{0}》初审未通过，初审意见为：<br/>{1}", article.Title, RefuseMessage)
                    //    });
                }
            }
            return false;
        }
        /// <summary>
        /// 为稿件查询可参与审稿的专家
        /// </summary>
        /// <param name="journal"></param>
        /// <param name="article"></param>
        /// <returns></returns>
        public static List<ExpertAndJobModel> FindExpertForExamine(Periodical journal, Article article, List<string> except)
        {
            using (Context ctx = new Context())
            {
                except = except == null ? new List<string>() : except;
                var leager = (from c in ctx.Organization
                              join e in ctx.Expert
                                 on c.UserName equals e.UserName
                              join u in ctx.User
                                 on c.UserName equals u.UserName
                              where c.ApplyStatus == 1 && c.OrgType == (int)OrganizationType.Journal && c.OrgId == journal.Id && c.Status == 2 //&& !except.Contains(c.UserName)
                              select new
                              {
                                  ExperUserName = c.UserName,
                                  ExpertName = u.NickName,
                                  JobCount = ctx.AuditingRecord.Count(i => new List<int>(){ 1, 2 }.Contains(i.ExamineStatus) && i.UserName == c.UserName)
                              }).ToList()
                             .Select(c => new ExpertAndJobModel() { 
                                ExpertName="B " + c.ExpertName,
                                ExpertUserName=c.ExperUserName,
                                JobCount=c.JobCount
                             })
                             .ToList();
                  var employ = (from c in ctx.Expert
                              join u in ctx.User
                                 on c.UserName equals u.UserName
                              where c.Profession == (int)journal.IndType
                              select new
                              {
                                  ExperUserName = c.UserName,
                                  ExpertName = "Z " + u.NickName,
                                  JobCount = ctx.AuditingRecord.Count(i => new List<int>() { 1, 2 }.Contains(i.ExamineStatus) && i.UserName == c.UserName)
                              }).ToList()
                                 .Select(c => new ExpertAndJobModel()
                                 {
                                     ExpertName = c.ExpertName,
                                     ExpertUserName = c.ExperUserName,
                                     JobCount = c.JobCount
                                 })
                                 .ToList();
                
                List<ExpertAndJobModel> Res = new List<ExpertAndJobModel>();
                var list = leager.Union(employ);
                foreach (var item in list)
                {
                    if (!Res.Any(c => c.ExpertUserName == item.ExpertUserName))
                    {
                        Res.Add(item);
                    }
                }
                return Res;
            }
        }
        public static List<Appendix> GetArticleAttachment(Expression<Func<T_Appendix, bool>> where)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.Appendix.Where(where).OrderBy(c => c.Id).ToList()
                    .Select(c => new Appendix().Set(c))
                    .ToList();
                return list;
            }
        }
        #endregion

        #region 期刊链接
        public static FriendLink GetLink(int Id)
        {
            return new FriendLink().Find(Id.ToString());
        }
        public static List<FriendLink> GetAllLinks(Expression<Func<T_FriendLink, bool>> where, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.FriendLink
                    .Where(where)
                    .OrderByDescending(c => c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new FriendLink().Set(c))
                    .ToList();
                return list;
            }
        }
        public static int GetAllLinksForPage(Expression<Func<T_FriendLink, bool>> where)
        {
            using (Context ctx = new Context())
            {
                return ctx.FriendLink.Count(where);
            }
        }

        public static FriendLink SaveNewFriendLink(FriendLink entity)
        {
            if (entity != null)
            {
                return entity.PostAdd();
            }
            return null;
        }
        #endregion

        #region 期刊成员管理
        public static List<Organization> GetAllLeaguer(int journalId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.Organization
                            join u in ctx.User
                             on c.UserName equals u.UserName
                            join e in ctx.Expert
                             on c.UserName equals e.UserName
                            where c.OrgId == journalId && c.OrgType == (int)OrganizationType.Journal && c.ApplyStatus == 1 && c.Status == (int)JournalStatus.Counsellor
                            orderby c.Id
                            select new { c, u, e }
                           )
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => 
                               new Organization().Set(c.c)
                                .LoadUser(
                                    new User().Set(c.u),
                                    new Expert().Set(c.e)))
                           .ToList();
                return list;
            }
        }
        public static int GetAllLeaguerForPage(int journalId)
        {
            using (Context ctx = new Context())
            {
                return ctx.Organization.Count(c => c.OrgId == journalId && c.OrgType == (int)OrganizationType.Journal);
            }
        }
        /// <summary>
        /// 邀请站内专家
        /// </summary>
        /// <param name="expertAccount"></param>
        /// <param name="journal"></param>
        /// <returns></returns>
        public static bool DoInviteForExpert(string expertAccount, int journal)
        {
            var item = new Organization().Find(c => c.OrgId == journal && c.OrgType == (int)OrganizationType.Journal && c.UserName == expertAccount && c.Status == (int)JournalStatus.Counsellor);
            //如果已经存在 且已经通过确认
            if (item != null && item.ApplyStatus == 1)
            {
                return false;
            }
            //如果不存在
            else if(item == null)
            {
                item = new Organization()
                {
                    ApplyStatus = 0,
                    JoinDate = DateTime.Now,
                    OrgId = journal,
                    OrgType= OrganizationType.Journal,
                    Status = JournalStatus.Counsellor,
                    UserName = expertAccount
                }.PostAdd();
            }
            //如果还未处理。重发邮件
            if (item.ApplyStatus == 0)
            {
                var journalEntity = new Periodical().Find(journal.ToString());
                string toExpert = EmailBuilder.BuildInviteForExpertEmail(TaskType.NoticeToExpert,
                   expertAccount, OrganizationType.Journal, journalEntity.Name, journalEntity.Id, item.Id);
                if (!String.IsNullOrEmpty(toExpert))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                       new NormalNotifyEmail()
                       {
                           Recipient = expertAccount,
                           Title = "《" + journalEntity.Name + "》 邀请您加入编委会",
                           Message = toExpert
                       });
                }
                //WorkPool.Append<InviteForJournalNotityEmail>(WorkType.email_for_inviteexpert_notity,
                //    new InviteForJournalNotityEmail()
                //    {
                //        Type = (int)TaskType.NoticeToExpert,
                //        JournalId = journal,
                //        JournalLeaguerId = item.Id,
                //        JournalName = journalEntity.Name,
                //        Recipient = expertAccount
                //    });
            }
            return true;
        }
        /// <summary>
        /// 邀请站外专家
        /// </summary>
        /// <param name="expertAccount"></param>
        /// <param name="journal"></param>
        /// <returns>0：发送邀请失败 1：发送邀请成功 2：已经是本站专家 3：已经是本站会员 4</returns>
        public static int MailToInviteForExpert(string expertAccount, int journal)
        {
            var user = new User().Find(expertAccount);
            if (user != null)
            {
                if (user.IsActivate)
                {
                    if (user.SystemRole == UserRole.Expert)
                    {
                        return 2;
                    }
                    else
                    {
                        return 3;
                    }
                }
            }
            else
            {
                //占用账号名额
                new User()
                {
                    Area = AreaCode.BeiJing,
                    Birthday = DateTime.Parse("1970-01-01"),
                    Email = expertAccount,
                    Gender = Gender.Male,
                    IsActivate = false,
                    IsRefuse = false,
                    Location = Location.BeiJing,
                    NickName = "专家",
                    Password = AesAlgorithm.Encrypt("123456"),
                    SystemRole = UserRole.Expert,
                    RcdDate = DateTime.Now,
                    UserName = expertAccount
                }.PostAdd();
            }
            Organization item = new Organization().Find(c => c.OrgId == journal && c.OrgType == (int)OrganizationType.Journal && c.UserName == expertAccount && c.Status == 2 && c.ApplyStatus == 0);
            if (item == null)
            {
                item = new Organization()
                {
                    ApplyStatus = 0,
                    JoinDate = DateTime.Now,
                    OrgId = journal,
                    OrgType= OrganizationType.Journal,
                    Status = JournalStatus.Counsellor,
                    UserName = expertAccount
                }.PostAdd();
            }
            var journalEntity = new Periodical().Find(journal.ToString());
            string toExpert = EmailBuilder.BuildInviteForExpertEmail(TaskType.NoticeToExpert,
                    expertAccount, OrganizationType.Journal, journalEntity.Name, journalEntity.Id, item.Id);
            if (!String.IsNullOrEmpty(toExpert))
            {
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                   new NormalNotifyEmail()
                   {
                       Recipient = expertAccount,
                       Title = "《" + journalEntity.Name + "》 邀请您加入编委会",
                       Message = toExpert
                   });
            }

            //WorkPool.Append<InviteForJournalNotityEmail>(WorkType.email_for_inviteexpert_notity,
            //    new InviteForJournalNotityEmail()
            //    {
            //        Type = (int)TaskType.NoticeToExpert,
            //        JournalId = journal,
            //        JournalLeaguerId = item.Id,
            //        JournalName = journalEntity.Name,
            //        Recipient = expertAccount
            //    });
            return 1;
        }
        /// <summary>
        /// 重发专家邀请邮件
        /// </summary>
        /// <param name="account"></param>
        //public static void ReMailToInviteExpert(string account, int journalId)
        //{
        //    var journalEntity = new Periodical().Find(journalId.ToString());
        //    var invite = new Organization().Find(c => c.OrgId == journalId && c.OrgType == (int)OrganizationType.Journal && c.UserName == account && c.Status == 2 && c.ApplyStatus == 0);
        //    if (invite != null)
        //    {
        //        WorkPool.Append<InviteForJournalNotityEmail>(WorkType.email_for_invitereviser_notity,
        //         new InviteForJournalNotityEmail()
        //         {
        //             Type = (int)TaskType.NoticeToExpert,
        //             JournalId = journalId,
        //             JournalLeaguerId = invite.Id,
        //             JournalName = journalEntity.Name,
        //             Recipient = account
        //         });
        //    }
        //}
        /// <summary>
        /// 邀请专家响应处理方法
        /// </summary>
        /// <param name="agree"></param>
        /// <param name="expertAccount"></param>
        /// <param name="journalId"></param>
        /// <param name="journalLeaguerId"></param>
        /// <param name="user">如果是站内专家。user必然为null</param>
        /// <param name="expert">如果已经是专家，则此值为null.否则不为null</param>
        /// <returns></returns>
        public static bool ConfirmInviteForExpert(TaskType taskType, bool agree, string expertAccount, int journalId, int journalLeaguerId,User user = null, Expert expert=null)
        {
            Organization org = null;
            if (taskType == TaskType.NoticeToExpert)
            {
                org = new Organization().Find(c => c.Id == journalLeaguerId && c.OrgType == (int)OrganizationType.Journal && c.OrgId == journalId && c.UserName == expertAccount && c.ApplyStatus == 0 && c.Status == (int)JournalStatus.Counsellor);
            }
            else if (taskType == TaskType.MeetingToExpert)
            {
                org = new Organization().Find(c => c.Id == journalLeaguerId && c.OrgType == (int)OrganizationType.Meeting && c.OrgId == journalId && c.UserName == expertAccount && c.ApplyStatus == 0 && c.Status == (int)JournalStatus.Counsellor);
            }
            if (org == null || org.ApplyStatus != 0)
            {
                return false;
            }
            if (agree)
            {
                org.ApplyStatus = 1;
                org.Message = "";
            }
            else
            {
                org.ApplyStatus = 2;
                org.Message = "他（她）拒绝了邀请";
            }
            //if (user != null)
            //{
            //    var userIndb = new User().Find(expertAccount);
            //    if (userIndb != null)
            //    {
            //        user.SystemRole = UserRole.Expert;
            //        user.PostModify();
            //    }
            //    else
            //    {
            //        user.SystemRole = UserRole.Expert;
            //        user = UserBiz.Register(user, true);
            //    }
            //}
            //else
            //{
            //    user = new User().Find(expertAccount);
            //    if (user.SystemRole != UserRole.Expert)
            //    {
            //        user.SystemRole = UserRole.Expert;
            //        if (user.PostModify() == null)
            //        {
            //            LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, "修改用户：" + expertAccount + " 角色为UserRole.Expert时失败。请技术处理");
            //        }
            //    }
            //}
            //if (expert != null)
            //{
            //    if (!new Expert().Any(c => c.UserName == expert.UserName))
            //    {
            //        expert.PostAdd();
            //    }
            //}
            if (taskType == TaskType.NoticeToExpert)
            {
                var journal = new Periodical().Find(journalId.ToString());
                string toExpert = EmailBuilder.BuildWelcomeForExpertEmail(
                    expertAccount, OrganizationType.Journal, journal.Name);
                if (!String.IsNullOrEmpty(toExpert))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                    new NormalNotifyEmail()
                    {
                        Message = toExpert,
                        Title = "欢迎您加入"+journal.Name,
                        Recipient = expertAccount
                    });
                }
                //WorkPool.Append<WelcomeForExpertEmail>(WorkType.email_for_welcomeExpert,
                //    new WelcomeForExpertEmail()
                //    {
                //        Type = 0,
                //        JournalName = journal.Name,
                //        Recipient = expertAccount
                //    });
            }
            else if (taskType == TaskType.MeetingToExpert)
            {
                var meeting = new Meeting().Find(journalId.ToString());
                string toExpert = EmailBuilder.BuildWelcomeForExpertEmail(
                   expertAccount, OrganizationType.Journal, meeting.Name);
                if (!String.IsNullOrEmpty(toExpert))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                    new NormalNotifyEmail()
                    {
                        Message = toExpert,
                        Title = "欢迎您加入" + meeting.Name,
                        Recipient = expertAccount
                    });
                }
                //WorkPool.Append<WelcomeForExpertEmail>(WorkType.email_for_welcomeExpert,
                //    new WelcomeForExpertEmail()
                //    {
                //        Type = 0,
                //        JournalName = meeting.Name,
                //        Recipient = expertAccount
                //    });
            }
            return org.PostModify() != null;
        }
        public static void RefuseInviteExpert(int leagerid, int journalId, string expertAccount)
        {
            var item = new Organization().Find(c => c.Id == leagerid && c.OrgType == (int)OrganizationType.Journal && c.OrgId == journalId && c.UserName == expertAccount 
                && c.Status == (int)JournalStatus.Counsellor && c.ApplyStatus == 0);
            if (item != null)
            {
                item.ApplyStatus = 2;
                item.Message = "他（她）拒绝了您的邀请";
                item.PostModify();

                //删除临时占用账号
                var user = new User().Find(expertAccount);
                if (!user.IsActivate)
                {
                    user.PostDelete();
                }
            }
        }
        /// <summary>
        /// 移除管委会成员
        /// </summary>
        /// <param name="journalId"></param>
        /// <param name="userName"></param>
        public static void CancelEditorial(int journalId, string userName)
        {
            var item = new Organization().Find(c => c.OrgId == journalId && c.OrgType == (int)OrganizationType.Journal && c.UserName == userName && c.Status == (int)JournalStatus.Counsellor);
            if (item != null)
            {
                if (item.PostDelete() == null)
                {
                    LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "期刊id:" + journalId + " 删除用户：" + userName + " 为管委会成员失败。请技术处理");
                }
            }
        }
        public static List<Organization> GetAllReviser(int journalId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.Organization
                            join u in ctx.User
                             on c.UserName equals u.UserName
                            where c.OrgId == journalId && c.OrgType == (int)OrganizationType.Journal && c.ApplyStatus == 1 && c.Status == (int)JournalStatus.Reviser
                            orderby c.Id
                            select new { c, u}
                           )
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c =>
                               new Organization().Set(c.c)
                                .LoadUser(new User().Set(c.u),null))
                           .ToList();
                return list;
            }
        }
        /// <summary>
        /// 邀请站内会员加入初审员
        /// </summary>
        /// <param name="UserAccount"></param>
        /// <param name="journalId"></param>
        /// <returns></returns>
        //public static bool DoInviteForRevoser(string UserAccount, int journalId)
        //{
        //    var item = new Organization().Find(c => c.OrgId == journalId && c.OrgType == (int)OrganizationType.Journal && c.UserName == UserAccount && c.Status == (int)JournalStatus.Reviser);
        //    //如果已经存在 且已经通过确认
        //    if (item != null && item.ApplyStatus == 1)
        //    {
        //        return false;
        //    }
        //    //如果不存在
        //    else if (item == null)
        //    {
        //        item = new Organization()
        //        {
        //            ApplyStatus = 0,
        //            JoinDate = DateTime.Now,
        //            OrgId = journalId,
        //            OrgType= OrganizationType.Journal,
        //            Status = JournalStatus.Reviser,
        //            UserName = UserAccount
        //        }.PostAdd();
        //    }
        //    var journalEntity = new Periodical().Find(journalId.ToString());
        //    WorkPool.Append<InviteForJournalNotityEmail>(WorkType.email_for_invitereviser_notity,
        //        new InviteForJournalNotityEmail()
        //        {
        //            Type = 1,
        //            JournalId = journalId,
        //            JournalLeaguerId = -1,
        //            JournalName = journalEntity.Name,
        //            Recipient = UserAccount
        //        });
        //    return true;
        //}
        ///// <summary>
        ///// 邀请新会员加入初审
        ///// </summary>
        ///// <param name="UserAccount"></param>
        ///// <param name="journalid"></param>
        ///// <returns></returns>
        //public static bool MailToInviteForReviser(string UserAccount, int journalId)
        //{
        //    if (new User().Find(UserAccount) != null)
        //    {
        //        return false;
        //    }

        //    Organization item = new Organization()
        //    {
        //        ApplyStatus = 0,
        //        JoinDate = DateTime.Now,
        //        OrgId = journalId,
        //        OrgType = OrganizationType.Journal,
        //        Status = JournalStatus.Reviser,
        //        UserName = UserAccount
        //    }.PostAdd();

        //    var journalEntity = new Periodical().Find(journalId.ToString());
        //    WorkPool.Append<InviteForJournalNotityEmail>(WorkType.email_for_invitereviser_notity,
        //     new InviteForJournalNotityEmail()
        //     {
        //         Type = 1,
        //         JournalId = journalId,
        //         JournalLeaguerId = -1,
        //         JournalName = journalEntity.Name,
        //         Recipient = UserAccount
        //     });
        //    return true;
        //}
       
        ///// <summary>
        ///// 邀请专家响应处理方法
        ///// </summary>
        ///// <param name="agree"></param>
        ///// <param name="expertAccount"></param>
        ///// <param name="journalId"></param>
        ///// <param name="journalLeaguerId"></param>
        ///// <param name="user">如果是站内专家。user必然为null</param>
        ///// <param name="expert">如果已经是专家，则此值为null.否则不为null</param>
        ///// <returns></returns>
        //public static bool ConfirmInviteForReviser(bool agree, string expertAccount, int journalId, int journalLeaguerId, User user = null)
        //{
        //    var org = new Organization().Find(c => c.OrgId == journalId && c.OrgType == (int)OrganizationType.Journal && c.UserName == expertAccount && c.Status == (int)JournalStatus.Reviser);
        //    if (org == null || org.ApplyStatus != 0)
        //    {
        //        return false;
        //    }
        //    if (agree)
        //    {
        //        org.ApplyStatus = 1;
        //        org.Message = "";
        //    }
        //    else
        //    {
        //        org.ApplyStatus = 2;
        //        org.Message = "他（她）拒绝了邀请";
        //    }
        //    if (user != null)
        //    {
        //        var userIndb = new User().Find(expertAccount);
        //        if (userIndb == null)
        //        {
        //            user = UserBiz.Register(user, true);
        //        }
        //    }
        //    var journal = new Periodical().Find(journalId.ToString());
        //    WorkPool.Append<WelcomeForExpertEmail>(WorkType.email_for_welcomeExpert,
        //        new WelcomeForExpertEmail()
        //        {
        //            Type = 1,
        //            JournalName = journal.Name,
        //            Recipient = expertAccount
        //        });
        //    return org.PostModify() != null;
        //}
        public static void CancelResiver(int journalId, string userName)
        {
            var item = new Organization().Find(c => c.OrgId == journalId && c.OrgType == (int)OrganizationType.Journal && c.UserName == userName && c.Status == (int)JournalStatus.Reviser);
            if (item != null)
            {
                if (item.PostDelete() == null)
                {
                    LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "期刊id:" + journalId + " 删除用户：" + userName + " 为初审成员失败。请技术处理");
                }
            }
        }
        public static List<Organization> GetAllPendingMember(int journalId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.Organization
                            where c.OrgId == journalId && c.OrgType == (int)OrganizationType.Journal && c.ApplyStatus != 1
                            orderby c.Id
                            select new { c}
                           )
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c =>
                               new Organization().Set(c.c))
                           .ToList();
                return list;
            }
        }
        #endregion

        #region 审稿
        public static List<AuditingRecord> GetAllAuditingRecord(int articleId)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.AuditingRecord
                            where c.ManuscriptId == articleId
                            join m in ctx.User
                            on c.UserName equals m.UserName
                            select new { c , m.NickName})
                           .ToList()
                           .Select(c => { 
                               var item = new AuditingRecord().Set(c.c);
                               item.ExpertRealName = c.NickName;
                               return item; 
                           })
                           .ToList();
                return data;  
            }
        }
        public static List<AuditingRecord> GetAllAuditingRecord(int articleId, Expression<Func<T_AuditingRecord, bool>> where)
        {
            using (Context ctx = new Context())
            {
                var data = ctx.AuditingRecord
                    .Where(c=>c.ManuscriptId == articleId)
                    .Where(where)
                    .Join(ctx.User,
                    e => e.UserName,
                    m => m.UserName,
                    (e, m) => new { e, m.NickName })
                    .ToList()
                    .Select(c =>
                    {
                        var item = new AuditingRecord().Set(c.e);
                        item.ExpertRealName = c.NickName;
                        return item;
                    })
                    .ToList();
                return data;
            }
        }
        /// <summary>
        /// 稿件分配
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="experts"></param>
        public static void DoDistribution(int articleId, DateTime finishDate, string expert)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated &&
                !String.IsNullOrEmpty(expert) && !String.IsNullOrEmpty(expert))
            {
                var user = new User().Find(HttpContext.Current.User.Identity.Name);
                if (user.SystemRole == UserRole.Admin || user.SystemRole == UserRole.JounalsAdmin)
                {
                    var article = new Article().Find(articleId.ToString());
                    if (article != null)
                    {
                        var journal = new Periodical().Find(article.Peri_Id.ToString());
                        if (journal.Admin.ToLower() == HttpContext.Current.User.Identity.Name.ToLower() ||
                            user.SystemRole == UserRole.Admin)
                        { 
                            switch(article.Status)
                            {
                                //专审待分配                                
                                case ArticleStatus.ZhuanShenDaiFenPei:
                                    string[] experts = expert.Split(';');
                                    List<Expert> prof = new List<Expert>();
                                    foreach (var item in experts)
                                    {
                                        if (String.IsNullOrEmpty(item))
                                        {
                                            continue;
                                        }
                                        var spcl = new Expert().Find(item);
                                        if (spcl == null)
                                        {
                                            continue;
                                        }
                                        prof.Add(spcl);
                                    }

                                    foreach (var item in prof)
                                    {
                                        var auditingRecord = new AuditingRecord()
                                        {
                                            CreateTime = DateTime.Now,
                                            Distributor = HttpContext.Current.User.Identity.Name,
                                            ExamineStatus = ExamineStatus.DaiShenHe,
                                            JournalId = journal.Id,
                                            ManuscriptId = article.Id,
                                            Step = ExamineStep.ZhuanShen,
                                            UserName = item.UserName,
                                            ExamineFinishDate=finishDate
                                        }.PostAdd();
                                        //给专家发邮件
                                        string toExpert = EmailBuilder.BuildReviewNotityEmail(article.Id,
                                            auditingRecord.Id, item.UserName, OrganizationType.Journal, finishDate.ToString("yyyy-MM-dd"));
                                        if (!String.IsNullOrEmpty(toExpert))
                                        {
                                            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                                new NormalNotifyEmail()
                                                {
                                                    Recipient = item.UserName,
                                                    Title = "专审邀请--《" + journal.Name + "》",
                                                    Message = toExpert
                                                });
                                        }
                                        //WorkPool.Append<ZhuanShenJobEmail>(WorkType.email_for_examinejobdistribution,
                                        //    new ZhuanShenJobEmail()
                                        //    {
                                        //        BackUrl = "/home/receivepostdata?token=" +
                                        //        EncodeByBase64.Encode(AesAlgorithm.Encrypt(new ExamineTokenModel()
                                        //        {
                                        //            ExamineId = auditingRecord.Id,
                                        //            ArticleId = article.Id,
                                        //            expertUsername = item.UserName
                                        //        }.ToJson())),
                                        //        //ExamineSheetPath = HttpContext.Current.Server.MapPath(journal.ExamineSheet),
                                        //        JournalName = journal.Name,
                                        //        ManuscriptPath = HttpContext.Current.Server.MapPath(new Appendix().FindLast(c => c.RaletionId == article.Id && c.Type == (int)AttachmentType.Manuscript).Path),
                                        //        ExamineFinishDate = finishDate,
                                        //        Recipient = item.UserName
                                        //    });
                                    }
                                    if (prof.Any())
                                    {
                                        new ArticleHistory()
                                        {
                                            CreateTime = DateTime.Now,
                                            CurrentStatus = ArticleStatus.ZhuanShen,
                                            ManuscriptId = article.Id,
                                            Message = "专审中",
                                            Operator = HttpContext.Current.User.Identity.Name,
                                            PreStatus = article.Status
                                        }.PostAdd();

                                        article.Status = ArticleStatus.ZhuanShen;
                                        article.PostModify();
                                    }
                                    break;
                                //专审完成，等待分配
                                case ArticleStatus.ZhuanShenWanCheng:
                                    break;
                                //专审修订完成，等待确认
                                case ArticleStatus.ZhuanShenXiuDingWanCheng:
                                    break;
                                //终审完成，等待分配
                                case ArticleStatus.ZhongShenWanCheng:
                                    break;
                                //终审修订完成，等待分配
                                case ArticleStatus.ZhongShenXiuDingWanCheng:
                                    break;
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 接受审稿单
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="expert"></param>
        /// <param name="p"></param>
        public static void DoReceiveExamineSheet(int examineId, int articleId, string expertUsername, 
            string type, string Originality, string Usefulness, string Soundness, 
            string LinguisticQuality, string resolution, string contribution, 
            string originalless, int verdict, string verdictcontent, string examineSheet)
        {
            var article = new Article().Find(articleId.ToString());
            var expert = new Expert().Find(expertUsername);
            var user = new User().Find(expert.UserName);
            var examineRecord = new AuditingRecord().Find(examineId.ToString());
            if (article == null || expert == null || user == null || examineRecord== null || examineRecord.ExamineStatus != ExamineStatus.DaiShenHe)
            {
                return;
            }
            //var journal = new Periodical().Find(article.Peri_Id.ToString());
            var file = HttpContext.Current.Request.Files[examineSheet];
            string appendixPath = string.Empty;
            string appendixName = string.Empty;
            string appendixCode = string.Empty;
            Appendix articleAppendix = new Appendix().FindLast(c => c.RaletionId == articleId && c.Type == (int)AttachmentType.Manuscript);
            Appendix attachment = null;
            if (file != null && file.ContentLength > 0)
            {
                appendixCode = new StreamFactory().BuildArticleExamineSheetStream(articleAppendix.AppendixCode, articleAppendix.Id);

                string basedir = string.Empty;
                if (article.ArticleType == ArticleType.Journal)
                {
                    var journal = new Periodical().Find(article.Peri_Id.ToString());
                    basedir = "/content/journal/" + journal.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
                }
                else if (article.ArticleType == ArticleType.Meeting)
                {
                    var meeting = new Meeting().Find(article.Conference_Id.ToString());
                    basedir = "/content/meeting/" + meeting.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
                }
                else
                {
                    return;
                }
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }
                var fileInfo = new FileInfo(file.FileName);

                string extendName = fileInfo.Extension;
                appendixName = fileInfo.Name.Replace(extendName, "");

                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + extendName));
                appendixPath = basedir + appendixCode + extendName;

                attachment = new Appendix()
                {
                    AttachmentType = AttachmentType.ExamineSheet,
                    AppendixCode = appendixCode,
                    CreateTime = DateTime.Now,
                    FileName = appendixName,
                    Own = expert.UserName,
                    Path = appendixPath,
                    RaletionId = examineRecord.Id
                }.PostAdd();
            }

            //string type, string Originality, string Usefulness, string Soundness, 
            //string LinguisticQuality, string resolution, string contribution, 
            //string originalless, int verdict, string verdictcontent, string examineSheet

            examineRecord.LastRecord = DateTime.Now;
            examineRecord.ExamineStatus = ExamineStatus.WanCheng;
            examineRecord.ManuscriptType = type;
            examineRecord.Originality = Originality;
            examineRecord.Usefulness = Usefulness;
            examineRecord.Soundness = Soundness;
            examineRecord.LinguisticQuality = LinguisticQuality;
            examineRecord.Resolution = resolution.Replace("\r\n","<br/>");
            examineRecord.Contribution = contribution.Replace("\r\n", "<br/>");
            examineRecord.Originalless = originalless.Replace("\r\n", "<br/>");
            examineRecord.SuggestStatus = (ExamineSuggest)verdict;
            examineRecord.Suggestion = verdictcontent.Replace("\r\n", "<br/>");
            if (attachment != null)
            {
                examineRecord.AppendixId = attachment.Id;
            }
            examineRecord.PostModify();

            //给专家发感谢审稿邮件
            string toExpert = EmailBuilder.BuildTkForExamineEmail(article.Id,
                article.ArticleType == ArticleType.Journal ? OrganizationType.Journal : OrganizationType.Meeting,
                examineRecord.UserName);
            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                new NormalNotifyEmail()
                {
                    //BackUrl = "/workspace/console/article?type=0",
                    Message = toExpert,
                    Title = "感谢您的审稿意见",
                    Recipient = examineRecord.UserName
                });

            //var remain = new AuditingRecord().Count(c => 
            //    c.ManuscriptId == examineRecord.ManuscriptId && 
            //    c.Step == (int)examineRecord.Step &&
            //    c.ExamineStatus == 1);
            //if (remain == 0)
            //{
            //    if (article.Status == ArticleStatus.ZhuanShen) 
            //    {
            //        article.Status = ArticleStatus.ZhuanShenWanCheng;
            //        article.PostModify();

            //        new ArticleHistory()
            //        {
            //            CreateTime = DateTime.Now,
            //            CurrentStatus = ArticleStatus.ZhuanShenWanCheng,
            //            ManuscriptId = article.Id,
            //            Message = "专审完成",
            //            Operator = HttpContext.Current.User.Identity.Name,
            //            PreStatus = article.Status
            //        }.PostAdd();
            //        //给作者发邮件
            //        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
            //            new NormalNotifyEmail()
            //            {
            //                Recipient = article.UserName,
            //                Title = "您的稿件专审完成",
            //                Message = String.Format("您的稿件《{0}》专审已经完成，等待期刊管理员验收。如有疑问请尽快与期刊方联系。", article.Title)
            //            });
            //    }
            //}
        }
        /// <summary>
        /// 取消审核权限
        /// </summary>
        /// <param name="examineRecordId"></param>
        public static void CancelExamineForArticle(int examineRecordId)
        {
            string userName = HttpContext.Current.User.Identity.Name;
            var user = new User().Find(userName);
            if (String.IsNullOrEmpty(userName) || user == null)
            {
                return;
            }

            var record = new AuditingRecord().Find(examineRecordId.ToString());
            if (record == null)
            {
                return;
            }

            var journal = new Periodical().Find(c => c.Id == record.JournalId);
            if (journal == null || !(journal.Admin.ToLower() == userName.ToLower() || user.SystemRole == UserRole.Admin))
            {
                return;
            }

            record.ExamineStatus = ExamineStatus.QuXiao;
            record.Message = "管理员取消审核";
            record.PostModify();

            var article = new Article().Find(record.ManuscriptId.ToString());
            //给专家发邮件
            string toExpert = EmailBuilder.BuildCacnelExamineEmail(
                journal.Name, OrganizationType.Journal, article.Title);
            if (!String.IsNullOrEmpty(toExpert))
            {
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                  new NormalNotifyEmail()
                  {
                      Recipient = record.UserName,
                      Title = "管理员取消您的一项专审任务",
                      Message = toExpert
                  });
            }
        }
        public static AuditingRecord AppendExamineExpert(int articleId, string expert, DateTime finishDate)
        {
            string userName = HttpContext.Current.User.Identity.Name;
            var user = new User().Find(userName);
            var expertEntity = new User().Find(expert);
            if (String.IsNullOrEmpty(userName) || user == null || expertEntity== null)
            {
                return null;
            }

            var article = new Article().Find(articleId.ToString());
            if (article == null)
            {
                return null;
            }
            var journal = new Periodical().Find(c => c.Id == article.Peri_Id);
            if (journal == null || !(journal.Admin.ToLower() == userName.ToLower() || user.SystemRole == UserRole.Admin))
            {
                return null;
            }

            var auditingRecord = new AuditingRecord()
            {
                CreateTime = DateTime.Now,
                Distributor = HttpContext.Current.User.Identity.Name,
                ExamineStatus = ExamineStatus.DaiShenHe,
                JournalId = journal.Id,
                ManuscriptId = article.Id,
                Step = article.Status == ArticleStatus.ZhuanShen ? ExamineStep.ZhuanShen : ExamineStep.ZhongShen,
                UserName = expert,
                ExamineFinishDate = finishDate
            }.PostAdd();
            //给专家发邮件
            string toExpert = EmailBuilder.BuildReviewNotityEmail(article.Id,
                                            auditingRecord.Id, expert, OrganizationType.Journal, finishDate.ToString("yyyy-MM-dd"));
            if (!String.IsNullOrEmpty(toExpert))
            {
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                    new NormalNotifyEmail()
                    {
                        Recipient = expert,
                        Title = "专审邀请--《" + journal.Name + "》",
                        Message = toExpert
                    });
            }
            //WorkPool.Append<ZhuanShenJobEmail>(WorkType.email_for_examinejobdistribution,
            //    new ZhuanShenJobEmail()
            //    {
            //        BackUrl = "/home/receivepostdata?token=" +
            //        EncodeByBase64.Encode(AesAlgorithm.Encrypt(new ExamineTokenModel()
            //        {
            //            ExamineId = auditingRecord.Id,
            //            ArticleId = article.Id,
            //            expertUsername = expert
            //        }.ToJson())),
            //        ExamineSheetPath = HttpContext.Current.Server.MapPath(journal.ExamineSheet),
            //        JournalName = journal.Name,
            //        ManuscriptPath = HttpContext.Current.Server.MapPath(new Appendix().FindLast(c => c.RaletionId == article.Id && c.Type == (int)AttachmentType.Manuscript).Path),
            //        ExamineFinishDate = finishDate,
            //        Recipient = expert
            //    });
            return auditingRecord;
        }
        public static void urgeExamine(int auditingRecordId)
        {
            var auditingRecord = new AuditingRecord().Find(auditingRecordId.ToString());
            if (auditingRecord == null)
            {
                return;
            }
            var article = new Article().Find(auditingRecord.ManuscriptId.ToString());
            if (article == null)
            {
                return;
            }
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            if (journal == null)
            {
                return;
            }

            //给专家发催审邮件
            string toExpert = EmailBuilder.BuildUrgeExamineEmail(article.Id, auditingRecord.Id,
                 OrganizationType.Journal, auditingRecord.UserName);
            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                new NormalNotifyEmail()
                {
                    Message = toExpert,
                    Title = "稿件专审确认",
                    Recipient = auditingRecord.UserName
                });

            //给专家发催审邮件
            //WorkPool.Append<ZhuanShenJobEmail>(WorkType.email_for_urgeexamine,
            //    new ZhuanShenJobEmail()
            //    {
            //        BackUrl = "/home/receivepostdata?token=" +
            //        EncodeByBase64.Encode(AesAlgorithm.Encrypt(new ExamineTokenModel()
            //        {
            //            ExamineId = auditingRecord.Id,
            //            ArticleId = article.Id,
            //            expertUsername = auditingRecord.UserName
            //        }.ToJson())),
            //        ExamineSheetPath = HttpContext.Current.Server.MapPath(journal.ExamineSheet),
            //        JournalName = journal.Name,
            //        ManuscriptPath = HttpContext.Current.Server.MapPath(new Appendix().FindLast(c => c.RaletionId == article.Id && c.Type == (int)AttachmentType.Manuscript).Path),
            //        ExamineFinishDate = auditingRecord.ExamineFinishDate,
            //        Recipient = auditingRecord.UserName
            //    });
        }
        //public static bool FinishExamine(int articleId, int result, string msg)
        //{
        //    var user = new User().Find(HttpContext.Current.User.Identity.Name);
        //    var article = new Article().Find(articleId.ToString());
        //    if (user == null || article == null || article.Status != ArticleStatus.ZhuanShen)
        //    {
        //        return false;
        //    }
        //    var journal = new Periodical().Find(article.Peri_Id.ToString());
        //    if (journal == null || !(journal.Admin.ToLower() == HttpContext.Current.User.Identity.Name.ToLower() || user.SystemRole == UserRole.Admin))
        //    {
        //        return false;
        //    } 
        //    var attachment = new Appendix().Find(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
        //    if (attachment != null)
        //    {
        //        attachment.Suggestion = msg;
        //        attachment.PostModify();
        //    }
        //    if (result == 0) //专审通过
        //    {
        //        new ArticleHistory()
        //        {
        //            CreateTime = DateTime.Now,
        //            CurrentStatus = ArticleStatus.ZhuanShenWanCheng,
        //            ManuscriptId = article.Id,
        //            Message = "专审完成",
        //            Operator = HttpContext.Current.User.Identity.Name,
        //            PreStatus = article.Status
        //        }.PostAdd();
        //        var records = new AuditingRecord().FindAll(c => c.ManuscriptId == article.Id && c.Step == 2 &&
        //            new List<int>() { 1, 2 }.Contains(c.ExamineStatus));
        //        foreach (var item in records)
        //        {
        //            item.Message = "管理员结束专审";
        //            item.ExamineStatus = ExamineStatus.QuXiao;
        //            item.PostModify();
        //            //给专家发邮件
        //            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
        //                new NormalNotifyEmail()
        //                {
        //                    Recipient = item.UserName,
        //                    Title = "管理员取消您的一项专审任务",
        //                    Message = String.Format("《{0}》管理员结束了对于稿件《{1}》的专审工作，您无需再提交审稿结果。如有疑问请尽快与期刊方联系。", journal.Name, article.Title)
        //                });
        //        }
        //        article.Status = ArticleStatus.ZhuanShenWanCheng;
        //        article.PostModify();
        //        //给作者发邮件
        //        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
        //            new NormalNotifyEmail()
        //            {
        //                Recipient = article.UserName,
        //                Title = "您的稿件专审完成",
        //                Message = String.Format("您的稿件《{0}》专审已经完成，等待期刊管理员验收。如有疑问请尽快与期刊方联系。", article.Title)
        //            });
        //    }
        //    else if (result == 1) //专审修订
        //    {
        //        //先完成，再修订
        //        new ArticleHistory()
        //        {
        //            CreateTime = DateTime.Now,
        //            CurrentStatus = ArticleStatus.ZhuanShenWanCheng,
        //            ManuscriptId = article.Id,
        //            Message = "专审完成",
        //            Operator = HttpContext.Current.User.Identity.Name,
        //            PreStatus = article.Status
        //        }.PostAdd();

        //        new ArticleHistory()
        //        {
        //            CreateTime = DateTime.Now,
        //            CurrentStatus = ArticleStatus.ZhuanShenXiuDing,
        //            ManuscriptId = article.Id,
        //            Message = "专审修订",
        //            Operator = HttpContext.Current.User.Identity.Name,
        //            PreStatus = article.Status
        //        }.PostAdd();
        //        var records = new AuditingRecord().FindAll(c => c.ManuscriptId == article.Id && c.Step == 2 && c.ExamineStatus != 3);
        //        foreach (var item in records)
        //        {
        //            item.Message = "管理员结束专审";
        //            item.ExamineStatus = ExamineStatus.QuXiao;
        //            item.PostModify();
        //            //给专家发邮件
        //            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
        //                new NormalNotifyEmail()
        //                {
        //                    Recipient = item.UserName,
        //                    Title = "管理员取消您的一项专审任务",
        //                    Message = String.Format("《{0}》管理员结束了对于稿件《{1}》的专审工作，您无需再提交审稿结果。如有疑问请尽快与期刊方联系。", journal.Name, article.Title)
        //                });
        //        }
        //        article.Status = ArticleStatus.ZhuanShenXiuDing;
        //        article.PostModify();
        //        //给作者发邮件
        //        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
        //            new NormalNotifyEmail()
        //            {
        //                Recipient = article.UserName,
        //                Title = "您的稿件专审完成，需要修订",
        //                Message = String.Format("您的稿件《{0}》专审已完成，但需要您进行专审修订。<br/>{1}", article.Title, msg)
        //            });
        //    }
        //    else
        //    {
        //        //先完成，再拒绝
        //        new ArticleHistory()
        //        {
        //            CreateTime = DateTime.Now,
        //            CurrentStatus = ArticleStatus.ZhuanShenWanCheng,
        //            ManuscriptId = article.Id,
        //            Message = "专审完成",
        //            Operator = HttpContext.Current.User.Identity.Name,
        //            PreStatus = article.Status
        //        }.PostAdd();

        //        new ArticleHistory()
        //        {
        //            CreateTime = DateTime.Now,
        //            CurrentStatus = ArticleStatus.Close,
        //            ManuscriptId = article.Id,
        //            Message = "专审不通过",
        //            Operator = HttpContext.Current.User.Identity.Name,
        //            PreStatus = article.Status
        //        }.PostAdd();
        //        var records = new AuditingRecord().FindAll(c => c.ManuscriptId == article.Id && c.Step == 2 && c.ExamineStatus != 3);
        //        foreach (var item in records)
        //        {
        //            item.Message = "管理员结束专审";
        //            item.ExamineStatus = ExamineStatus.QuXiao;
        //            item.PostModify();
        //            //给专家发邮件
        //            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
        //                new NormalNotifyEmail()
        //                {
        //                    Recipient = item.UserName,
        //                    Title = "管理员取消您的一项专审任务",
        //                    Message = String.Format("《{0}》管理员结束了对于稿件《{1}》的专审工作，您无需再提交审稿结果。如有疑问请尽快与期刊方联系。", journal.Name, article.Title)
        //                });
        //        }
        //        article.Status = ArticleStatus.Close;
        //        article.PostModify();
        //        //给作者发邮件
        //        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
        //            new NormalNotifyEmail()
        //            {
        //                Recipient = article.UserName,
        //                Title = "您的稿件专审不通过",
        //                Message = String.Format("您的稿件《{0}》专审不通过。<br/>{1}", article.Title, msg)
        //            });
        //    }
        //    return true;
        //}
        /// <summary>
        /// 验收
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="result">0:进入终审 1：要求专审修订 9：专审不通过</param>
        /// <param name="msg"></param>
        /// <returns> 0：失败 1：成功 2：重新分配专审 </returns>
        public static int AcceptanceExamine(int articleId, int result, string msg,params int[] records)
        {
            var user = new User().Find(HttpContext.Current.User.Identity.Name);
            var article = new Article().Find(articleId.ToString());
            if (user == null || article == null)
            {
                return 0;
            }
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            if (journal == null || !(journal.Admin.ToLower() == HttpContext.Current.User.Identity.Name.ToLower() || user.SystemRole == UserRole.Admin))
            {
                return 0;
            }
            var attachment = new Appendix().FindLast(c => c.RaletionId == article.Id && c.Type == (int)AttachmentType.Manuscript);
            if (attachment == null)
            {
                return 0;
            }
            //进入终审
            if (result == 0) 
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhongShen,
                    ManuscriptId = article.Id,
                    Message = "终审中",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                new AuditingRecord() { 
                    CreateTime=DateTime.Now,
                    Distributor=HttpContext.Current.User.Identity.Name,
                    ExamineStatus = ExamineStatus.DaiShenHe,
                    JournalId= journal.Id,
                    ManuscriptId=article.Id,
                    Message="终审分配",
                    Step= ExamineStep.ZhongShen,
                    UserName = HttpContext.Current.User.Identity.Name
                }.PostAdd();

                article.Status = ArticleStatus.ZhongShen;
                article.PostModify();
                //给作者发邮件
                string toAuthor = EmailBuilder.BuildZhuanShenFinishEmail(article.Title);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Recipient = article.UserName,
                            Title = "您的稿件进入终审阶段",
                            Message = toAuthor
                        });
                }
            }
            else if (result == 1) //要求专审修订
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhuanShenXiuDing,
                    ManuscriptId = article.Id,
                    Message = "专审修订",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.ZhuanShenXiuDing;
                article.PostModify();

                string suggestion = BuildZhuanShenResultContent(article.Id,
                    "要求专审修订",
                    msg,
                    records);
                attachment.Suggestion = suggestion;
                attachment.PostModify();
                
                //给作者发邮件
                string toAuthor = EmailBuilder.BuildRevisionForAuthorEmail(article.Id, OrganizationType.Journal, suggestion);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Recipient = article.UserName,
                            Title = "您的稿件需要修订",
                            Message = toAuthor
                        });
                }
            }
            else if (result == 2) //重新分配专审
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhuanShenDaiFenPei,
                    ManuscriptId = article.Id,
                    Message = "重新分配专审",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.ZhuanShenDaiFenPei;
                article.PostModify();
                return 2;
            }
            else if (result == 9)
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.Close,
                    ManuscriptId = article.Id,
                    Message = "专审不通过",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.Close;
                article.PostModify();

                string suggestion = BuildZhuanShenResultContent(article.Id,
                   "专审不通过",
                   msg,
                   records);
                attachment.Suggestion = suggestion;
                attachment.PostModify();

                //给作者发邮件
                string toAuthor = EmailBuilder.BuildZhuanShenRefuseEmail(
                    article.Title, suggestion);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Recipient = article.UserName,
                            Title = "您的稿件专审不通过",
                            Message = toAuthor//String.Format("您的稿件《{0}》专审不通过。<br/>{1}", article.Title, suggestion)
                        });
                }
            }


            var list = new AuditingRecord().FindAll(c => c.JournalId == journal.Id && c.ManuscriptId == articleId
                && c.Step == (int)ExamineStep.ZhuanShen && c.ExamineStatus == (int)ExamineStatus.DaiShenHe);
            if (list.Any())
            {
                foreach (var item in list)
                {
                    item.ExamineStatus = ExamineStatus.QuXiao;
                    item.PostModify();

                    //给专家发邮件
                    string toExpert = EmailBuilder.BuildCacnelExamineEmail(journal.Name,
                         OrganizationType.Journal, article.Title);
                    if (!String.IsNullOrEmpty(toExpert))
                    {
                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                            new NormalNotifyEmail()
                            {
                                Recipient = item.UserName,
                                Title = "期刊 \"" + journal.Name + "\" 取消您对于稿件《" + article.Title + "》的审稿资格",
                                Message = toExpert//String.Format("期刊《{0}》取消您对于稿件《{1}》的审稿资格，如有疑问请与期刊方联系。", journal.Name, article.Title)
                            });
                    }
                }
            }
            return 1;
        }
        /// <summary>
        /// 终审验收
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="result"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool ConclusiveExamine(int articleId, int totalPay, int result, string msg)
        {
            var user = new User().Find(HttpContext.Current.User.Identity.Name);
            var article = new Article().Find(articleId.ToString());
            if (user == null || article == null)
            {
                return false;
            }
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            if (journal == null || !(journal.Admin.ToLower() == HttpContext.Current.User.Identity.Name.ToLower() || user.SystemRole == UserRole.Admin))
            {
                return false;
            }
            if (result == 0)
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhongShenWanCheng,
                    ManuscriptId = article.Id,
                    Message = "终审通过",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                var record = new AuditingRecord().Find(c => c.ManuscriptId == article.Id && c.Step == 3 && c.ExamineStatus == 1);

                if (record != null)
                {
                    record.ExamineStatus = ExamineStatus.WanCheng;
                    record.LastRecord = DateTime.Now;
                    record.PostModify();
                }

                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.LuYong,
                    ManuscriptId = article.Id,
                    Message = "录用",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.LuYong;
                article.PostModify();

                var bill = new Reckoning()
                {
                    CreateTime = DateTime.Now,
                    Message = String.Format("期刊《{0}》出版费用", article.Title),
                    Own = article.UserName,
                    PayFor = 0,
                    RaletionId = article.Id,
                    Status = 0,
                    TotalPay = totalPay
                }.PostAdd();
                if (bill == null)
                {
                    LogHelper.Write(CommonLogger.Journal, LogLevel.Error,
                        "稿件" + article.Id + "记录代缴费记录失败，请人工处理");
                }

                string toAuthor = EmailBuilder.BuildAcceptanceNotityEmail(article.Id, totalPay, OrganizationType.Journal);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                       new NormalNotifyEmail()
                       {
                           Recipient = article.UserName,
                           Title = "您的稿件已被录用",
                           Message = toAuthor
                       });
                }
                //WorkPool.Append<PublicationEmail>(WorkType.email_for_publication,
                //   new PublicationEmail()
                //   {
                //       ArticleName = article.Title,
                //       Recipient = article.UserName,
                //       Message = String.Format("您的稿件《{0}》已终审通过且被录用，现需要您支付{1}元的版面费，在您缴费以后期刊方将为您安排出版。如有疑问请与期刊方联系。",
                //       article.Title, totalPay),
                //       BackUrl = "/workspace/member/bill"
                //   });
            }
            else if (result == 1)
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhongShenXiuDing,
                    ManuscriptId = article.Id,
                    Message = "终审修订",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.ZhongShenXiuDing;
                article.PostModify();

                var att = new Appendix().FindLast(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
                att.Suggestion = msg;
                att.PostModify();

                //给作者发邮件
                string toAuthor = EmailBuilder.BuildRevisionForAuthorEmail(article.Id, OrganizationType.Journal, msg);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Recipient = article.UserName,
                            Title = "您的稿件需要修订",
                            Message = toAuthor
                        });
                }
                //WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                //    new NormalNotifyEmail()
                //    {
                //        Recipient = article.UserName,
                //        Title = "您的稿件终审完成，需要修订",
                //        Message = String.Format("您的稿件《{0}》已通过管理员终审验收但需要您进行终审修订。<br/>{1}", article.Title, msg)
                //    });
            }
            else if (result == 9)
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.Close,
                    ManuscriptId = article.Id,
                    Message = "终审不通过",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.Close;
                article.PostModify();

                var att = new Appendix().FindLast(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
                att.Suggestion = msg;
                att.PostModify();

                //给作者发邮件
                string toAuthor = EmailBuilder.BuildZhongShenRefuseEmail(
                    article.Title,msg);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Recipient = article.UserName,
                            Title = "您的稿件终审不通过",
                            Message = toAuthor
                        });
                }
            }
            return true;
        }
        public static void OverExamie(int articleId, string controlName)
        {
            var article = new Article().Find(articleId.ToString());
            if (article != null && article.Status == ArticleStatus.ChuBanYiJiaoFei)
            {
                var journal = new Periodical().Find(article.Peri_Id.ToString());

                var file = HttpContext.Current.Request.Files[controlName];
                string appendixPath = string.Empty;
                string appendixName = string.Empty;
                string appendixCode = string.Empty;
                string format = string.Empty;
                string size = string.Empty;
                if (file != null && file.ContentLength > 0)
                {
                    appendixCode = new StreamFactory().BuildArticleAppendixCodeStreamNo(
                        article.Code, AttachmentStatus.DingGao, article.Id);
                    string basedir = "/content/journal/" + journal.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                    }

                    var fileInfo = new FileInfo(file.FileName);
                    size = Math.Round(
                        decimal.Parse(file.ContentLength.ToString()) / 1024,
                        2).ToString() + " KB";
                    string extendName = fileInfo.Extension;
                    format = extendName.Replace(".", "").ToUpper();
                    appendixName = fileInfo.Name.Replace(extendName, "");

                    file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + extendName));
                    appendixPath = basedir + appendixCode + extendName;

                    //创建附件
                    var attachment = new Appendix()
                    {
                        AttachmentType = AttachmentType.Manuscript,
                        AppendixCode = appendixCode,
                        CreateTime = DateTime.Now,
                        FileName = appendixName,
                        Path = appendixPath,
                        Own = HttpContext.Current.User.Identity.Name,
                        RaletionId = article.Id,
                        AttachmentStatus = AttachmentStatus.DingGao,
                        Format = format,
                        Size = size
                    };
                    attachment.PostAdd();

                    new ArticleHistory() { 
                        CreateTime=DateTime.Now,
                        CurrentStatus= ArticleStatus.DaiChuBan,
                        ManuscriptId=article.Id,
                        Message="定稿",
                        Operator=HttpContext.Current.User.Identity.Name,
                        PreStatus=article.Status
                    }.PostAdd();

                    article.Status = ArticleStatus.DaiChuBan;
                    article.PostModify();
                    if (attachment == null)
                    {
                        LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "保存定稿附件失败，请手工处理" + Environment.NewLine + attachment.ToJson());
                    }
                }
            }
        }
        public static string BuildZhuanShenResultContent(int articleId,string examineResult,string suggestion, int[] examineId)
        {
            List<AuditingRecord> sheet = new List<AuditingRecord>();
            if (examineId != null && examineId.Any())
            {
                sheet = GetAllAuditingRecord(articleId, c => examineId.Contains(c.Id));
            }
            var article = new Article().Find(articleId.ToString());
            StringBuilder sb = new StringBuilder();
            sb.Append("<div style=\"width: 700px; height: auto;\">");
            if (article != null)
            {
                sb.Append("<fieldset>");
                sb.Append("<legend>专审验收结果</legend>");
                sb.Append("<div style=\"width: 650px; margin-left: auto; margin-right: auto;\">");
                sb.Append("<div style=\"width: 100%; border-bottom: 1px solid #ccc;\">");
                sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%; border-bottom: 1px solid #eee;\">");
                sb.Append("<div style=\"width: 30%; float: left;\">稿件名：</div>");
                sb.Append(String.Format("<div>{0}</div>", article.Title));
                sb.Append("</div>");
                sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%; border-bottom: 1px solid #eee;\">");
                sb.Append("<div style=\"width: 30%; float: left;\">专审结论：</div>");
                sb.Append(String.Format("<div>{0}</div>", examineResult));
                sb.Append("</div>");
                sb.Append("<div style=\"display: block; height: auto; width: 100%;\">");
                sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">专审意见： </div>");
                sb.Append("<div style=\"display: block; height: auto; width: 100%; word-break: break-all; text-indent: 20px;\">");
                sb.Append(String.Format("<p>{0}</p>", suggestion));
                sb.Append("</div>");
                sb.Append("</div>");
                sb.Append("</div>");
                sb.Append("</div>");
                sb.Append("</fieldset>");
                sb.Append("<br/>");
            }
            if (sheet != null && sheet.Any())
            {
                char index = 'A';
                foreach (var item in sheet)
                {
                    sb.Append("<fieldset>");
                    sb.Append("<legend>" + index++ + "专家意见</legend>");
                    sb.Append("<div style=\"width: 650px; margin-left: auto; margin-right: auto;\">");
                    sb.Append("<div style=\"width: 100%; border-bottom: 1px solid #ccc;\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div style=\"width: 30%; float: left;\">1、稿件类型：</div>");
                    sb.Append(String.Format("<div>{0}</div>",item.ManuscriptType));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"width: 100%; border-bottom: 1px solid #ccc;\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div>2、总体评价：</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div style=\"width: 20%; float: left;\">1）原创性：</div>");
                    sb.Append(String.Format("<div style=\"width: 20%; float: left;\">{0}</div>",item.Originality));
                    sb.Append("<div style=\"width: 20%; float: left;\">2）实用性：</div>");
                    sb.Append(String.Format("<div style=\"width: 20%; float: left;\">{0}</div>",item.Usefulness));
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div style=\"width: 20%; float: left;\">3）技术合理性：</div>");
                    sb.Append(String.Format("<div style=\"width: 20%; float: left;\">{0}</div>",item.Soundness));
                    sb.Append("<div style=\"width: 20%; float: left;\">4）语言描述：</div>");
                    sb.Append(String.Format("<div style=\"width: 20%; float: left;\">{0}</div>",item.LinguisticQuality));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"width: 100%; border-bottom: 1px solid #ccc;\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div>3、稿件说明：</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">1)、稿件解决了什么问题？</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%; word-break: break-all; text-indent: 20px;\">");
                    sb.Append(String.Format("<p>{0}</p>",item.Resolution));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">2)、主要领域作出的贡献？</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%; word-break: break-all; text-indent: 20px;\">");
                    sb.Append(String.Format("<p>{0}</p>",item.Contribution));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("3)、在哪些方面确实缺乏原创？");
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%; word-break: break-all; text-indent: 20px;\">");
                    sb.Append(String.Format("<p>{0}</p>",item.Originalless));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"width: 100%; border-bottom: 1px solid #ccc;\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div style=\"width: 30%; float: left;\">4、最终评审：</div>");
                    sb.Append(String.Format("<div>{0}</div>",item.SuggestStatus.Mapping()));
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">总体意见：</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%; word-break: break-all; text-indent: 20px;\">");
                    sb.Append(String.Format("<p>{0}</p>",item.Suggestion));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("</fieldset>");
                    sb.Append("<br/>");
                }
            }
            sb.Append("</div>");
            return sb.ToString();
        }
        #endregion

        #region 稿件出版
        public static PeriodicalItem NewJournalItem(int journalId, string manuscriptcode, string publishDate)
        {
            var journal = new Periodical().Find(journalId.ToString());
            if (journal != null)
            {
                var item = new PeriodicalItem() { 
                    CreateDate=DateTime.Now,
                    Manuscriptcode=manuscriptcode,
                    PublishDate=DateTime.Parse(publishDate),
                    Status = JournalItemStatus.Create,
                    PeriodicalId = journalId
                }.PostAdd();
                return item;
            }
            return null;
        }
        public static void DeleteJournalItem(int journalId, int journalItemId)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var username = HttpContext.Current.User.Identity.Name;
                var user = new User().Find(username);
                var journal = new Periodical().Find(journalId.ToString());
                if (user != null && (username.ToLower() == journal.Admin.ToLower() || user.SystemRole == UserRole.Admin))
                {
                    var journalItem = new PeriodicalItem().Find(journalItemId.ToString());
                    if (journalItem != null)
                    {
                        using (Context ctx = new Context())
                        {
                            ctx.Update<T_Article>()
                                .Set(c => c.PeriItem_Id, DBNull.Value)
                                .WhereSet(c => c.PeriItem_Id, WhereOperator.Equal, journalItem.Id)
                                .End()
                                .Excute();
                            var allArticleId = ctx.Article.Where(c => c.PeriItem_Id == journalItem.Id).Select(c => c.Id).ToList();
                            var articleCache = new ArticleCache();
                            allArticleId.ForEach(c =>
                            {
                                articleCache.RefreshItem(c.ToString());
                            });
                        }
                        journalItem.PostDelete();
                    }
                }
            }           
        }
        public static List<PeriodicalItem> GetAllJournalItem(int journalId,int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.PeriodicalItem
                            join a in ctx.Article
                                on c.Id equals a.PeriItem_Id into o
                            from i in o.DefaultIfEmpty()
                            where c.PeriodicalId == journalId
                            group new { c, i } by c.Id into g
                            orderby g.Key descending
                            select g)
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c=>new PeriodicalItem()
                               .Set(c.FirstOrDefault().c)
                               .SetArticles(c.Where(o=>o.i != null).Select(o=>new Article().Set(o.i)).ToList()))
                           .ToList();
                return data;
            }
        }
        public static List<PeriodicalItem> GetAllPublishedJournalItem(int journalId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.PeriodicalItem
                            join a in ctx.Article
                                on c.Id equals a.PeriItem_Id into o
                            from i in o.DefaultIfEmpty()
                            where c.PeriodicalId == journalId && c.Status == (int)JournalItemStatus.Publish
                            group new { c, i } by c.Id into g
                            orderby g.Key descending
                            select g)
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new PeriodicalItem()
                               .Set(c.FirstOrDefault().c)
                               .SetArticles(c.Where(o => o.i != null).Select(o => new Article().Set(o.i)).ToList()))
                           .ToList();
                return data;
            }
        }
        /// <summary>
        /// 稿件出版
        /// </summary>
        /// <param name="journalItemId"></param>
        /// <returns>0:失败，1:成功，2:期刊被禁用 </returns>
        public static int PublishJournalItem(int journalItemId)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var journalItem = new PeriodicalItem().Find(journalItemId.ToString());
                if(journalItem != null){
                    var journal = new Periodical().Find(journalItem.PeriodicalId.ToString());
                    if (!journal.IsActive)
                    {
                        return 2;
                    }
                    string username = HttpContext.Current.User.Identity.Name;
                    var user = new User().Find(username);
                    if (user != null && (journal.Admin.ToLower() == username.ToLower() || user.SystemRole == UserRole.Admin))
                    {
                        journalItem.Status = JournalItemStatus.Publish;
                        journalItem.PostModify();

                        using (Context ctx = new Context())
                        {
                            ctx.Update<T_Article>()
                                .Set(c => c.Status, (int)ArticleStatus.YiChuBan)
                                .WhereSet(c => c.PeriItem_Id, WhereOperator.Equal, journalItemId)
                                .End()
                                .Excute();
                            var allArticleId = ctx.Article.Where(c => c.PeriItem_Id == journalItemId).Select(c => c.Id).ToList();
                            var articleCache = new ArticleCache();
                            string toMember = string.Empty;
                            allArticleId.ForEach(c => {
                                Article article = new Article().Find(c.ToString());
                                toMember = EmailBuilder.BuildBeenPublishEmail(c, OrganizationType.Journal, journalItemId, article);
                                if (!String.IsNullOrEmpty(toMember))
                                {
                                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                        new NormalNotifyEmail()
                                        {
                                            //BackUrl = "/workspace/console/article?type=0",
                                            Message = toMember,
                                            Title = String.Format("您的稿件 \"{0}\" 已出版", article.Title),
                                            Recipient = article.UserName
                                        });
                                }

                                articleCache.RefreshItem(c.ToString());
                            });
                        }
                    }
                    return 1;
                }
            }
            return 0;
        }
        public static int GetAllJournalItemForPage(int journalId)
        {
            return new PeriodicalItem().Count(c => c.PeriodicalId == journalId);
        }
        public static int GetAllPublishedJournalItemForPage(int journalId)
        {
            return new PeriodicalItem().Count(c => c.Id == journalId && c.Status == (int)JournalItemStatus.Publish);
        }
        public static PeriodicalItem GetNewJournalItemDetail(int journalId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var journalItem = (from c in ctx.PeriodicalItem
                                   where c.PeriodicalId == journalId && c.Status == (int)JournalItemStatus.Publish
                                   orderby c.Id descending
                                   select c)
                                  .FirstOrDefault();
                if (journalItem == null)
                {
                    return null;
                }
                PeriodicalItem item = new PeriodicalItem().Set(journalItem);
                var articles = (from c in ctx.Article
                                join a in ctx.ArticleAuthor
                                    on c.Id equals a.ManuscriptId
                                join m in ctx.Appendix
                                    on c.Id equals m.RaletionId
                                where m.Type == 1 && c.PeriItem_Id == journalItem.Id && !c.IsDelete && c.Status == (int)ArticleStatus.YiChuBan
                                group new { c, a, m } by c.Id into g
                                orderby g.Key
                                select g)
                               .Skip(page * pageSize)
                               .Take(pageSize)
                               .ToList()
                               .Select(c =>
                                   new Article()
                                   .Set(c.FirstOrDefault().c)
                                   .LoadArticleAuthor(
                                        c.Select(o => new ArticleAuthor()
                                         .Set(o.a)).ToList())
                                   .LoadAttachment(
                                        c.Select(i =>new Appendix().Set(i.m)).ToList()
                                   ))
                               .ToList();
                item.SetArticles(articles);
                return item;
            }
        }
        public static void AddArticleToPublish(int articleId, int journalItemId)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var username = HttpContext.Current.User.Identity.Name;
                var user = new User().Find(username);
                var journalItem = new PeriodicalItem().Find(journalItemId.ToString());
                if (journalItem != null)
                {
                    var journal = new Periodical().Find(journalItem.PeriodicalId.ToString());
                    if (journal != null && user != null && (journal.Admin.ToLower() == username.ToLower() || user.SystemRole == UserRole.Admin))
                    {
                        var article = new Article().Find(articleId.ToString());
                        article.PeriItem_Id = journalItemId;
                        article.PostModify();
                    }
                }
            }
        }
        #endregion

        /// <summary>
        /// true:不存在重复，可用
        /// false:存在重复，不可用
        /// </summary>
        /// <param name="shortname"></param>
        /// <param name="type">1：期刊 2：会议</param>
        /// <returns></returns>
        public static bool ShortNameIsExists(string shortname, int type)
        {
            using (Context ctx = new Context())
            {
                bool exists = false;
                if (type == 1)
                {
                    exists = !ctx.Periodical.Any(c => c.ShortName == shortname);
                }
                else
                {
                    exists = !ctx.Meeting.Any(c => c.ShortName == shortname);
                }
                if (!exists) {
                    return exists;
                }
                exists = !ctx.User.Any(c => c.UserName == shortname + "@csaep.org");
                return exists;
            }
        }
    }
}
